import { execSync } from 'child_process'
import { program } from 'commander'
import { decode } from 'iconv-lite'
import { exec } from 'sudo-prompt'

function remove() {
  const index = program.args[1]
  const result = execSync('netsh interface portproxy show all', {
    encoding: 'buffer'
  })
  const data = decode(result, 'gbk') // 从第 5 行开始是数据
  const lines = data.split('\r\n').slice(5) // 去掉空行
  const list = lines.filter(Boolean).map(line => {
    const [listen, port, wslListen, wslPort] = line.split(/\s+/)
    return {
      '宿主机 ipv4': listen,
      宿主机端口: port,
      'wsl ipv4': wslListen,
      wsl端口: wslPort
    }
  })
  // 判断index是否合法
  if (isNaN(Number(index))) {
    console.log('index不合法')
    return
  }
  if (Number(index) < 0 || Number(index) >= list.length) {
    console.log('index不合法')
    return
  }
  // 删除端口映射
  exec(
    `netsh interface portproxy delete v4tov4 listenaddress=${
      list[Number(index)]['宿主机 ipv4']
    } listenport=${list[Number(index)].宿主机端口}`,
    {
      name: 'netsh wsl'
    },
    function (error, stdout, stderr) {
      if (error) throw error
      require('../ls/index')
      console.log(`Remove-NetFirewallRule -DisplayName "Allow Inbound TCP Port ${list[Number(index)].宿主机端口}"`);

    }
  )
}

remove()
